#!/usr/bin/python

import sys
import os
import re
import mutagen 
import mutagen.id3
from mutagen.id3 import ID3, TIT2, TPE1, TALB, TCOM, TPUB, TRCK, TDRC, TXXX, \
                        TCON, COMM
from discogs import Discogs
from tag_lib import Playlist

# Character substitutions in file name
CHAR_EXCEPTIONS = {
            '&' : 'and',
             ' ' : '_',
             '#' : 'Number',
            }

# supported file types.
FILE_TYPE = ['.mp3']

def prep_files(dir, rem=0):
    """
    Places file names into a list, and removes unwanted
    crud..
    """
    
    fL = []
    try:
        dList = os.listdir(dir)
        dList.sort()
    except OSError:
        print "[ERROR] no such directory"
        sys.exit()
    for f in dList:
        for t in FILE_TYPE:
            if f.lower().endswith(t):
                fL.extend([dir + '/' + f])
            elif rem == 1:
                os.remove(dir + "/" + f)
    return fL

def clean_file(f):
    """
        Removes unwanted characters from file names
    """
    a = unicode(f).encode("utf-8")

    for k,v in CHAR_EXCEPTIONS.iteritems():
        a = a.replace(k, v)

    cf = re.compile(r'[^-\w.\(\)_]')
    return cf.sub('', str(a))

if __name__ == "__main__":

    if len(sys.argv) != 3:
        print "Usage: py_tag.py <folder of mp3s> <discogs release id>"
        sys.exit()

    files = prep_files(sys.argv[1],1)
    disc = Discogs(sys.argv[2])
    tot = str(len(disc.track_list))
   
    # ensure length of tracks on disk match length
    # of tracks obtained from the discogs API 
    if len(files) != len(disc.track_list):
        print "[ERROR] : local tracklist does not match discogs tracklist, aborting."
        sys.exit()

    c = 0
    pl = []
    print "[INF] removing old ID3 tags, and adding new entries"
    for f in files:
        # remove ID3 tags
        try:
            audio = ID3(f)
            audio.delete()
        except mutagen.id3.ID3NoHeaderError:
            pass
        # add new ID3 tags 
        try:
            id3 = mutagen.id3.ID3(f)
        except mutagen.id3.ID3NoHeaderError:
            id3 = mutagen.id3.ID3()

        # adding new id3 frames
        id3.add(TIT2(encoding=3, text=disc.track_list[c][2]))
        id3.add(TPE1(encoding=3, text=disc.track_list[c][1]))
        id3.add(TALB(encoding=3, text=disc.title))
        id3.add(TCOM(encoding=3, text=disc.artist))
        id3.add(TPUB(encoding=3, text=disc.label))
        id3.add(TDRC(encoding=3, text=disc.year))
        id3.add(TXXX(encoding=3, desc='Catalog #', text=disc.cat_num))
        id3.add(TCON(encoding=3, text=disc.genre))
        id3.add(TRCK(encoding=3, text=str("%.2d/%s" % (int(disc.track_list[c][0]), tot))))
        id3.add(COMM(encoding=3, desc='eng', text='::> Don\'t believe the hype! <::'))
        id3.save(f,0)
        
        # new file name : directory/DD-ARTIST-TITLE.mp3 
        nf = "%.2d-%s-%s.mp3" % (int(clean_file(disc.track_list[c][0])),
              clean_file(disc.track_list[c][1]),
              clean_file(disc.track_list[c][2]))
        os.rename(f, "%s/%s" % (sys.argv[1],nf))
        
        # append details to playlist list
        pl.append([nf,'%s - %s' % (disc.track_list[c][1], 
                  disc.track_list[c][2])]) 
        c += 1

    print "[INF] renaming files, and directory"
    nd = "%s-%s-(%s)-%s-jW" % (clean_file(disc.artist), clean_file(disc.title),
                               clean_file(disc.cat_num), clean_file(disc.year)) 
    os.rename(sys.argv[1], nd)

    nfo = open(nd + "/00-" + clean_file(disc.artist) + "-" + \
            clean_file(disc.title) + ".nfo", "w")
    nfo.write(unicode(disc.disc_debug()).encode("utf-8"))
    nfo.close()

    print "[INF] Creating playlist..."
    m3u = Playlist(pl, clean_file(disc.artist), clean_file(disc.title))
    m3u.wrt_m3u(nd)

    print "[INF] complete."
    print disc.disc_debug()
